package com.fundamentalesandroid;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.content.res.AssetManager;
import java.io.InputStream;
import java.io.IOException;
import java.io.ByteArrayOutputStream;

public class AssetsTest extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		TextView textView=new TextView(this);
		setContentView(textView);
		AssetManager assetManager=getAssets();
		InputStream inputStream=null;
		try {
			inputStream=assetManager.open("dir/dir2/texto.txt");
			String text=cargarArchivoTexto(inputStream);
			textView.setText(text);
		}catch (IOException e){
			textView.setText("No se pudo cargar el archivo texto.txt");
		} finally {
			if(inputStream != null){
				try{
					inputStream.close();
				}catch(IOException e){
					textView.setText("No se pudo cerrar el archivo");
				}
			}
		}
	}
	
	public String cargarArchivoTexto(InputStream inputStream)throws IOException{
		ByteArrayOutputStream byteStream=new ByteArrayOutputStream();
		byte[] bytes=new byte[4096];
		int len=0;
		while((len=inputStream.read(bytes))>0){
			byteStream.write(bytes,0,len);
		}
		return new String(byteStream.toByteArray(),"UTF8");
	}
	
	
}
